import axios from "axios";
import store from "@/store";
import { getToken} from '@/utils/auth'
import service from "../utils/request";
import Code from '@/utils/code'
const main = axios.create({
    baseURL: process.env.BASE_API,
    timeout: 5000,
    withCredentials: true //使前台能够保存cookie
});


const h5Axios = axios.create();
const file = axios.create({
    baseURL: process.env.FILE_API,
});
file.defaults.headers.post["Content-Type"] = "multipart/form-data";
//请求拦截器
main.interceptors.request.use(config => {
    if (store.getters.token) {
        config.headers['admin-token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    }
    return config
}, error => {
    console.log(error)
    Promise.reject(error)
});

/**
 * @author qun.xu
 * @desc   response登出。
 * @date   2019-01-11
 */
service.interceptors.response.use(
    /**
     * 下面的注释为通过response
     * 自定义code来标示请求状态，
     * 当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过XMLhttprequest 状态码标识 逻辑可写在下面error中
     */
    res => {
        if(res.data.code==0){
            return res;
        }else{
            if(res.data.code == Code.UNAUTHEN || res.data.code == Code.SESSION_TIMOUT){
                //处理登录相关的错误
                MessageBox.confirm('登陆已失效,请重新登陆！', '确定登出',
                    {confirmButtonText: '重新登录',cancelButtonText: '取消',type: 'warning'}).then(() => {
                    store.dispatch('FedLogOut').then(() => {
                        location.reload();// 为了重新实例化vue-router对象 避免bug
                    });
                })
            }else{
                //其它错误弹出错误信息
                Message({ message: res.data.msg, type: 'error', duration: 5000});
            }
            return Promise.reject('error');
        }
    },
    /**
     * 请求发生错误，一般都是服务器抛异常了
     */
    err => {
        console.error('request err: %o', err)// for debug
        Message({message: error.message,type: 'error',duration: 5000})
        return Promise.reject(error)
    }
)

const api = {
    axios,
    file(d) {
        let fromData = new FormData();
        fromData.append("file", d);
        return file.post("/uploadFile", fromData);
    },
    backLogin(phone, password){
        return  main.post(
            `admin/login?account=${phone}&password=${password}`
        )
    },
    listAdmin(params){
        return  main.get('/cms/admin/list',{params:params})
    },
    deleteAdmin(params){
        return  main.post('/cms/admin/delete',params)
    },
    saveAdmin(params){
        return  main.post('/cms/admin/save',params);
    },
    listRoles(params){
        return  main.get('/cms/role/list',{params:params})
    },
    deleteRole(params){
        return  main.post('/cms/role/delete',params)
    },
    saveRole(params){
        return  main.post('/cms/role/save',params);
    },
    getAdminRole(params){
        return  main.get('/cms/admin/role',{params:params});
    },
    saveAdminRole(params){
        return  main.post('/cms/admin/role/save',params);
    },
    login(params){
        return  main.post('/cms/user/login',params);
    },
    restPassword(params){
      return  main.post('/cms/admin/restPassword',params);
    },
    updatePassword(params){
      return  main.post('/cms/admin/password/update',params);
    },
    getBannerList(){
        return  main.get('/cms/banner/info');
    },
    saveBannerList(params){
        return main.post('/cms/banner/save',params);
    },
    //=====================字典管理=============================
    getSysConstantList(){
        return  main.get('/cms/sys/constant/list');
    },
    getConstantInfo(params){
        return  main.get('/cms/sys/constant/info',{params:params});
    },
    updateConstant(params){
        return  main.post('/cms/sys/constant/edit',params);
    },
    //=========卡车类型
    getTruckTypeDicList(params){
        return  main.get('/cms/dic/truck/type/list',{params:params});
    },
    deleteTruckType(params){
        return  main.post('/cms/dic/truck/type/delete',params);
    },
    saveOrUpdateTruckType(params){
        return  main.post('/cms/dic/truck/type/save',params);
    },
    getTruckTypeInfo(params){
        return  main.get('/cms/dic/truck/type/info',{params:params});
    },

    //=====================字典管理=============================
    //=========卡车发动机
    getTruckEngineDicList(params){
        return  main.get('/cms/dic/truck/engine/list',{params:params});
    },
    deleteTruckEngine(params){
        return  main.post('/cms/dic/truck/engine/delete',params);
    },
    saveOrUpdateTruckEngine(params){
        return  main.post('/cms/dic/truck/engine/save',params);
    },
    getTruckEngineInfo(params){
        return  main.get('/cms/dic/truck/engine/info',{params:params});
    },
    //=========卡车品牌维护
    getBrandTreeData(params){
        return  main.get('/cms/dic/truck/brand/tree',{params:params});
    },
    getRegion(params){
        return  main.get('/sys/regionList',{params:params});
    },
    getTruckType(){
        return  main.get('/truck/constant/truckType');
    },
    getTruckBrandParent(params){
        return  main.get('/truck/constant/parentBrand',{params:params});
    },
    getTruckBrand(params){
        return  main.get('/truck/constant/truckBrand',{params:params});
    },
    getTruckEnums(){
        return  main.get('/truck/constant/truckEnums');
    },
    getEngines(){
        return  main.get('/truck/constant/truckEngine');
    },
    saveTruck(params){
        return  main.post('/cms/truck/save',params);
    },
    listTrucks(params){
        return  main.get('/cms/truck/list',{params:params});
    },
    listUserTrucks(params){
        return  main.get('/cms/user/truck/list',{params:params});
    },
    listAudit(params){
        return  main.get('/cms/truck/audit/list',{params:params});
    },
    deleteTruck(params){
        return  main.post('/cms/truck/delete',params);
    },
    saveAudit(params){
        return  main.post('/cms/truck/saveAudit',params);
    },
    updateShelf(params){
        return  main.post('/cms/truck/updateShelf',params);
    },
    getTruckInfo(params){
        return  main.get('/cms/truck/info',{params:params});
    },
    visitorList(params){
        return  main.get('/cms/truck/visitorList',{params:params});
    },
    //=====================用户管理========================
    listUsers(params){
        return  main.get('/cms/user/list',{params:params})
    },
    deleteUser(params){
        return  main.post('/cms/user/delete',params)
    },
    updateUserStatus(params){
        return  main.post('/cms/user/updateStatus',params)
    },
    saveUser(params){
        return  main.post('/cms/user/saveOrUpdate',params)
    },
    userInfo(params){
        return  main.post('/cms/user/info',params)
    },
    listTruckBrand(params){
        return  main.get('/cms/truck/brand/list',{params:params})
    },
    deleteBrand(params){
        return  main.post('/cms/truck/brand/delete',params)
    },
    getBrandInfo(params){
        return  main.get('/cms/truck/brand/info',{params:params})
    },
    listChildren(params){
        return  main.get('/cms/truck/brand/children',{params:params})
    },
    saveBrand(params){
        return  main.post('/cms/truck/brand/save',params)
    },
    //=======================bannerList======================
    listBanner(params){
        return  main.get('/cms/banner/list')
    },
    deleteBanner(params){
        return  main.post('/cms/banner/delete',params)
    },
    saveBanner(params){
        return  main.post('/cms/banner/saveOrUpdate',params)
    },
    getBannerInfo(params){
        return  main.get('/cms/banner/info',{params:params})
    },
    loadSuggestUser(params){
        return  main.get('/cms/user/searchForTruck',{params:params});
    },
    //====================权限分配======================
    listAllPermissions(params){
        return main.get('/cms/sys/perm/list');
    },
    syncMenuPerms(params) {
        return main.post('/cms/sys/perm/sync/menu',params);
    },
    syncApiPerms(){
        return main.post('/cms/sys/perm/sync/api',params);
    },
    savePerm(params){
        return main.post('/cms/sys/perm/save',params);
    },
    deletePerm(params){
        return main.post('/cms/sys/perm/delete',params);
    },
    updatePerm(params){
        return main.post('/cms/sys/perm/update',params);
    },
    listApiPerm(){
        return main.get('/cms/sys/perm/api/list');
    },
    loadRolePerms(roleId){
        return main.get('/cms/role/'+roleId+'/perms');
    },
    listBtnGroupByParent(){
        return main.get('/cms/sys/perm/btn/group');
    },
    addRolePerm(params){
        return main.post('/cms/role/perm/add',params);
    },
    deleteRolePerm(params){
        return main.post('/cms/role/perm/delete',params);
    },
    saveRoleMenuPerm(params){
        return main.post('/cms/role/perm/menu',params);
    },
    //===============首页相关方法============================
    loadIndexData(){
        return main.get('/cms/index/data');
    }

}

export default api;
